package org.smart.framework.helper;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.smart.framework.util.ReflectionUtil;
import org.smart.framework.annotation.Inject;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * 依赖注入助手类
 * @Auther Uncle_Z
 * @date 2017/8/23 16:18
 * @Email:2545375@qq.com
 * @since 1.0
 * To change this template use File | Settings | File Templates.
 */

public final class IocHelper {

    static {
        //获取所有Bean类和Bean类实例之间的映射关系()
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();

        //检测map是否有值
        if (MapUtils.isNotEmpty(beanMap)) {
            for (Map.Entry<Class<?>, Object> entry : beanMap.entrySet()) { //遍历map获取Bean和bean实例
                Class<?> beanClass = entry.getKey();
                Object beanInstance = entry.getValue();
                Field[] beanFields = beanClass.getDeclaredFields(); //获取Bean的所有字段
                if (ArrayUtils.isNotEmpty(beanFields)) {
                    for (Field field : beanFields) {
                        if (field.isAnnotationPresent(Inject.class)) {//判断字段是否有Inject注解
                            Class<?> beanFieldClass = field.getType();
                            Object beanFieldInstance = beanMap.get(beanFieldClass); //获取map中字段的实例
                            if (beanFieldInstance != null) {
                                ReflectionUtil.setField(beanInstance, field, beanFieldInstance); //注入字段实例
                            }
                        }
                    }
                }
            }
        }
    }
}
